package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Sign;
import cn.wolfcode.trip.base.mapper.SignMapper;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.service.ISignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SignServiceImpl implements ISignService {

    @Autowired
    private SignMapper signMapper;
    @Autowired
    private UserMapper userMapper;


    @Override
    public void signByUser(Sign sign) {
        //判断今天是否签到了
        if (getSignTime(sign)==null){

            //创建时间
            sign.setSignTime(new Date());
            //签到状态
            sign.setState(1);

            //判断昨天是否签到
            if (getSignState(sign) == null){
                sign.setCount(1);
            }
            //如果昨天没有签到
            if (getSignState(sign) != null){
                //如果签到次数少于7次,次数都会加1
                if (sign.getCount() < 7){
                    sign.setCount(getSignState(sign).getCount() + 1);
                }

            }
            signMapper.insert(sign);

        }else {
            //判断
            throw new RuntimeException("今天已经签到");
        }
    }

    @Override
    public void sign(Sign sign) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int day = cal.get(Calendar.DAY_OF_MONTH);

        Sign sign1 = signMapper.selectByTime(day);
        if(sign1==null){
            signMapper.insert(sign);
        }else{
            throw new RuntimeException("今天已经签到");
        }
    }

    @Override
    public Map<String, Object> selectAllTime() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int d = cal.get(Calendar.DAY_OF_MONTH);
        System.out.println(d);

        List<Integer> days = signMapper.selectAllTime();


        int k = list(d, days);
        System.out.println(k);

        Map<String,Object> map = new HashMap<>();
        map.put("days",days);
        map.put("count",k);
        return map;
    }





    //判断昨天是否签到了
    public Sign getSignState(Sign sign){
        return signMapper.selectByYesterDay(sign.getUser().getId());
    }

    //判断今天是否签到
    public Sign getSignTime(Sign sign){
        return signMapper.getSignTime(sign.getUser().getId());
    }

    public static int list(int d ,List<Integer> days){

        Integer[] dayss = new Integer[days.size()];

        days.toArray(dayss);

        int k =0;
        for(int i=0; i<dayss.length;i++){
            if ((d-i)==dayss[i]){
                k++;
            }else{
                return k;
            }
        }
        return k;
    }

}
